<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input placeholder="请输入患者名名进行查询" style="width: 200px" v-model="data.patientName"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load()">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div class="table">
        <el-table :data="data.tableData" strip @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="id" label="药单ID" width="95" align="center" sortable></el-table-column>
          <el-table-column prop="patientName" label="患者姓名"></el-table-column>
          <el-table-column prop="visitId" label="就诊单ID"></el-table-column>
          <el-table-column prop="prescriptionDate" label="开药日期"></el-table-column>
          <el-table-column prop="totalCost" label="总价"></el-table-column>
          <el-table-column prop="notes" label="药单备注"  show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" align="center" width="400">
            <template v-slot="scope">
              <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">修改药单备注</el-button>
              <el-button size="mini" type="primary" plain @click="handelAddDrugs(scope.row)">添加药品</el-button>
              <el-button type="warning" @click="lookHadAddOuter(scope.row.id)" style="margin-top: 5px">查看当前已经添加的药品</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              style="margin-top: 5px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="data.pageNum"
              :page-sizes="[3, 5, 10, 15, 20]"
              :page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="data.total">
          </el-pagination>
        </div>
    </div>

      <el-dialog title="修改药单备注" v-model="data.formVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.form" label-width="150px" style="padding-right: 50px">
          <el-form-item label="药单备注" prop="notes">
            <el-input v-model="data.form.notes" placeholder="药单备注" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveNote()">保 存</el-button>
        </span>
        </template>
      </el-dialog>

      <el-dialog title="选择药品" v-model="data.drugsListVisible" width="75%"  :close-on-click-modal="false" destroy-on-close >

        <div class="card" style="margin-bottom: 5px">
          <el-input placeholder="请输入药品名进行查询" style="width: 200px" v-model="data.drugName"></el-input>
          <el-button type="info" plain style="margin-left: 10px" @click="loadDrug()">查询</el-button>
          <el-button type="warning" plain style="margin-left: 10px" @click="resetDrug">重置</el-button>
          <el-button type="primary" @click="lookHadAddInner" style="margin-top: 5px">查看当前已经添加的药品</el-button>

        </div>
        <div class="card">
            <el-table :data="data.drugData" strip  max-height="350px">
              <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
              <el-table-column prop="drugName" label="药品名"></el-table-column>
              <el-table-column prop="drugCategory" label="类别"></el-table-column>
              <el-table-column prop="specification" label="规格"></el-table-column>
              <el-table-column prop="unitPrice" label="单价"></el-table-column>
              <el-table-column prop="inventory" label="库存"></el-table-column>
              <el-table-column label="操作" align="center" width="180">
                <template v-slot="scope">
                  <el-button size="mini" type="primary" plain @click="handleAddDrug(scope.row)">添加</el-button></template>
              </el-table-column>
            </el-table>
          <div style="margin-top: 10px" class="pagination">
            <el-pagination
                style="margin-top: 5px"
                @size-change="handleSizeChangeDrug"
                @current-change="handleCurrentChangeDrug"
                :current-page="data.pageNumDrug"
                :page-sizes="[3, 5, 10, 15, 20]"
                :page-size="data.pageSizeDrug"
                layout="total, sizes, prev, pager, next, jumper"
                :total="data.totalDrug">
            </el-pagination>
          </div>
        </div>
      </el-dialog>

      <el-dialog title="添加药品" v-model="data.addDrugVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="data.addDrugForm" label-width="150px" style="padding-right: 50px" :rules="rules" ref="addForm">
          <el-form-item label="药单ID" prop="prescriptionId">
            <el-input v-model="data.addDrugForm.prescriptionId" placeholder="药单ID" disabled></el-input>
          </el-form-item>
          <el-form-item label="药品ID" prop="drugId">
            <el-input v-model="data.addDrugForm.drugId" placeholder="药品ID" disabled></el-input>
          </el-form-item>
          <el-form-item label="药品名" prop="drugName">
            <el-input v-model="data.addDrugForm.drugName" placeholder="药品ID" disabled></el-input>
          </el-form-item>
          <el-form-item label="单价" prop="unitPrice">
            <el-input v-model="data.addDrugForm.unitPrice" placeholder="单价" disabled></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="data.addDrugForm.quantity" placeholder="数量" min="1" :max="data.addDrugForm.inventory"></el-input-number><span> 该药品库存有{{data.addDrugForm.inventory}}件</span>
          </el-form-item>
          <el-form-item label="使用说明" prop="usageInstructions">
            <el-input v-model="data.addDrugForm.usageInstructions" placeholder="使用说明" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.addDrugVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAddDrugForm">保 存</el-button>
        </span>
        </template>
      </el-dialog>

      <el-dialog title="以下是已经添加的药品" v-model="data.hadAddVisited" width="70%" :close-on-click-modal="false" destroy-on-close>
        <div class="table">
          <el-table :data="data.itemData" strip >
            <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
            <el-table-column prop="prescriptionId" label="药单ID"></el-table-column>
            <el-table-column prop="drugId" label="药品ID"></el-table-column>
            <el-table-column prop="drugName" label="药品名"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column prop="unitPrice" label="单价"></el-table-column>
            <el-table-column prop="totalPrice" label="总价"></el-table-column>
            <el-table-column prop="usageInstructions" label="使用说明"></el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template v-slot="scope">
                <el-button size="mini" type="danger" plain @click="delItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'

// 定义响应式数据
const data = reactive({
  tableData: [],  // 表格数据
  pageNum: 1,     // 当前页码
  pageSize: 10,   // 每页显示数量
  total: 0,       // 总记录数
  patientName: null,     // 搜索条件
  formVisible: false, // 表单显示状态
  form: {},       // 表单数据
  addDrugForm: {},
  ids: [],        // 选中数据的ID
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  drugsListVisible: false,
  addDrugVisible: false,
  drugName: null,
  drugData: [],
  pageNumDrug: 1,     // 当前页码
  pageSizeDrug: 10,   // 每页显示数量
  totalDrug:0,
  drugItem: {},
  currentPrescriptionId: null,// 当前正在编辑的处方ID
  hadAddVisited: false,
  itemData: [],
})
const addForm = ref()

// 分页查询
const load = (pageNum = data.pageNum) => {
  data.pageNum = pageNum
  request.get('/prescription/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      patientName: data.patientName,
      doctorId: data.user.id,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 保存数据
const saveNote = () => {
  const url = data.form.id ? '/prescription/update' : '/prescription/add'
  const method = data.form.id ? 'PUT' : 'POST'
  request({
    url,
    method,
    data: data.form,
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('保存成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}


// 编辑数据
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}


// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 重置筛选条件
const reset = () => {
  data.patientName = null
  load()
}

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  load(pageNum)
}
const handleSizeChange=(pageSize)=> {
  data.pageSize = pageSize
  load()
}

// 页面初始化加载数据
load()

// 添加药品
const handelAddDrugs = (row) =>{
  data.currentPrescriptionId = row.id
  data.drugsListVisible = true
  loadDrug()
}
const handleAddDrug = (row) =>{
  if(row.inventory <= 0){
    ElMessage.error('该药品库存不足，无法添加！');
    return
  }
  data.addDrugForm = JSON.parse(JSON.stringify(row))
  data.addDrugForm.id = null // 新建ID置空
  data.addDrugForm.prescriptionId = data.currentPrescriptionId // 处方ID
  data.addDrugForm.drugId = row.id // 药品ID
  data.addDrugVisible = true
}

const submitAddDrugForm = () =>{
  addForm.value.validate((valid) => {
    if (valid) {
      saveAddDrugForm()
    } else {
      ElMessage.error('请填写必须的参数！');
      return false;
    }
  });
}
const saveAddDrugForm = () =>{
  console.log(data.addDrugForm)
  request.post('/prescriptionItem/add', data.addDrugForm).then(res => {
    if (res.code === '200') {
      data.addDrugVisible = false
      ElMessage.success('保存成功')
      data.addDrugForm = {}
      updateTotalPrice(data.currentPrescriptionId)
    } else {
      ElMessage.error(res.msg)
    }
})
}
const updateTotalPrice = (prescriptionId) =>{
  console.log(prescriptionId)
  request.get('/prescription/updateTotalPrice/'+ prescriptionId).then(res => {
    if (res.code === '200') {
      load()
      loadDrug()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 校验规则
const rules = {
  quantity: [
    { required: true, message: '请输入药品数量', trigger: 'blur' },
    { type: 'number', message: '药品数量必须为数字值'}
  ]
}


const lookHadAddInner = () =>{
  data.hadAddVisited = true
  loadItemInner()
}
const lookHadAddOuter = (prescriptionId) =>{
  data.hadAddVisited = true
  loadItemOuter(prescriptionId)
}

const delItem = (row) =>{
  ElMessageBox.confirm('您确定从该药单中删除这个药品吗？', '确认删除', { type: 'warning' }).then(() => {
    request.delete('/prescriptionItem/delete/' + row.id).then(res => {
      if (res.code === '200') {
        updateTotalPrice(row.prescriptionId)
        data.hadAddVisited = false
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {})
}
const loadDrug = () => {
  request.get('/drug/selectPage', {
    params: {
      pageNum: data.pageNumDrug,
      pageSize: data.pageSizeDrug,
      drugName: data.drugName,
    }
  }).then(res => {
    if (res.code === '200') {
      data.drugData = res.data?.list
      data.totalDrug = res.data?.total
      console.log(data.drugData)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const resetDrug = () => {
  data.drugName = null
  loadDrug()
}
// 处理页码变化
const handleCurrentChangeDrug = (pageNum) => {
  data.pageNumDrug = pageNum
  loadDrug()
}
const handleSizeChangeDrug = (pageSize)=> {
  data.pageSizeDrug = pageSize
  loadDrug()
}
loadDrug()

const loadItemInner = () => {
  request.get('/prescriptionItem/selectPage', {
    params: {
      pageNum: 1,
      pageSize: 1000,
      prescriptionId: data.currentPrescriptionId
    }
  }).then(res => {
    if (res.code === '200') {
      data.itemData = res.data?.list
      console.log(data.itemData)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const loadItemOuter = (prescriptionId) => {
  request.get('/prescriptionItem/selectPage', {
    params: {
      pageNum: 1,
      pageSize: 1000,
      prescriptionId: prescriptionId
    }
  }).then(res => {
    if (res.code === '200') {
      data.itemData = res.data?.list
      console.log(data.itemData)
    } else {
      ElMessage.error(res.msg)
    }
  })
}
</script>

